layui.use([ 'form', 'table', 'laydate'], function() {
	var form = layui.form;
	var table = layui.table;
	var laydate = layui.laydate;
	laydate.render({
		elem: '#timeText',
		range: true,
		done: function(value){
			$('#timeText').val(value);
			active.reload();
		}
	});
	
	
	var roleData;
	var $ = layui.$, active = {
		reload : function() {
			var nameText = $('#nameText');
			var timeText = $('#timeText');
			var projectTypeText = $('#projectTypeText');
			var platform_name = $('#platform_name');
			var project_name = $('#project_name');
			// 执行重载
			table.reload('userReload', {
				page : {
					curr : 1
				// 重新从第 1 页开始
				},
				where : {
					nameText : nameText.val(),
					timeText : timeText.val(),
					type_id : projectTypeText.val(),
					platform_name : platform_name.val(),
					project_name : project_name.val()
				}
			});
		}
	};
	
	var roleId = "";
	$.ajax({
		type: 'post',
	    url: '../../sysuser/findUserRole',
	    async: false,
	    success: function(result){
	        roleId = result.role_id;	
	    }		
	});
	
	/* 异步平台Select */
	var url = "../../sysrole/platformSelection";
	$.get(url, function(result) {
		var data = JSON.parse(result);
		var platform = data.platform;
		var roleSelect = $("#platform_name");
		$.each(platform, function(index, data) {
			var deptOption = $("<option value='" + data + "'>" + data + "</option>");
			roleSelect.append(deptOption);
		});
		form.render('select');
	});
	
	/* 异步项目Select */
	var url = "../../sysrole/projectSelection";
	$.get(url, function(result) {
		var data = JSON.parse(result);
		var project = data.project;
		var roleSelect = $("#project_name");
		$.each(project, function(index, data) {
			var deptOption = $("<option value='" + data + "'>" + data + "</option>");
			roleSelect.append(deptOption);
		});
		form.render('select');
	});

	/* 异步部门Select */
	var url = "../../sysrole/departmentSelection";
	$.get(url, function(result) {
		var data = JSON.parse(result);
		var departments = data.department;
		var roleSelect = $("#departmentSelect");
		$.each(departments, function(index, data) {
			var deptOption = $("<option value='" + data.dept_id + "'>" + data.dept_name + "</option>");
			roleSelect.append(deptOption);
		});
		form.render('select');
	});

	/* 异步项目类型Select */
	var url = "../../sysrole/projectTypeSelection";
	$.get(url, function(result) {
		var data = JSON.parse(result);
		var project_types = data.project_type;
		var roleSelect = $("#projectTypeSelect");
		$.each(project_types, function(index, data) {
			var deptOption = $("<option value='" + data.id + "'>" + data.type + "</option>");
			roleSelect.append(deptOption);
		});
		var projectTypeText = $("#projectTypeText");
		$.each(project_types, function(index, data) {
			var deptOption = $("<option value='" + data.id + "'>" + data.type + "</option>");
			projectTypeText.append(deptOption);
		});
		form.render('select');
	});
	

	form.on('select(departmentFilter)', function(data) {
		$.getJSON("../../sysrole/departmentStaffSelection?departmen_id=" + data.value, function(data) {
			var optionstring = "";
			$.each(data.sysuser, function(i, item) {
				optionstring += "<option value=\"" + item.id + "\" >" + item.name + "</option>";
			});
			$("#departmentStaffSelect").html('<option value=""></option>' + optionstring);
			form.render('select');
		});
	});

	table.render({
		elem : '#sysuserTable',
		url : '../../activiti/queryWholeProcessList',
		toolbar : '#toolbarSysuser',
		title : '任务表',
		cols : [ [ {
			type : 'checkbox',
			fixed : 'left'
		}, {
			field : 'pro',
			title : '项目编号',
			width : 100,
			fixed : 'left',
			unresize : true,
			sort : true
		},{
			field : 'name',
			title : '流程名称'
		}, {
			field : 'parent_name',
			title : '平台或项目名称'
		}, {
			field : 'type_id',
			title : '流程类型'
		}, {
			field : 'START_TIME_',
			title : '创建时间',
			sort : true
		}, {
			field : 'END_TIME_',
			title : '完成时间',
			sort : true,
			templet: function(d){if (typeof(d.END_TIME_) == "undefined") {return "-" }else {return d.END_TIME_}}
		}, {
			field : 'status',
			title : '状态',
			sort : true,
			templet: function(d){
				if(d.status=="1"){
					return "进行中";
				}else if (d.status=="0"){
					return "已删除";
				}else if(d.status=="2"){
					return "已完成";
				}
			}
		}, {
			fixed : 'right',
			title : '操作',
			width : roleId == "1" ? 200 : 150,
			templet : function(d){
				if(roleId == "1"){
					return "<a class='layui-btn layui-btn-xs' lay-event='edit'>详情</a>" + 
					"<a class='layui-btn layui-btn-warm layui-btn-xs' lay-event='operationRecord'>记录</a>"+
					"<a class='layui-btn layui-btn-danger layui-btn-xs' lay-event='del'>删除</a>"
				}else{
					return "<a class='layui-btn layui-btn-xs' lay-event='edit'>详情</a>" + 
					"<a class='layui-btn layui-btn-warm layui-btn-xs' lay-event='operationRecord'>记录</a>"
				}				
			}		
		} ] ],
		id : 'userReload',
		page : true,
		done : function() {
			$.getJSON("../../sysrole/projectTypeSelection", function(data) {
				var project_types = data.project_type;
				$("[data-field='type_id']").children().each(function() {
					for (var i = 0; i < project_types.length; i++) {
						if ($(this).text() == project_types[i].id) {
							$(this).text(project_types[i].type);
							break;
						}
					}
				});
			});
		}
	});

	// 头工具栏事件
	table.on('toolbar(sysuserTable)', function(obj) {
		var checkStatus = table.checkStatus(obj.config.id);
		switch (obj.event) {
		case 'getCheckData':
			var data = checkStatus.data;
			layer.alert(JSON.stringify(data));
			break;
		case 'getCheckLength':
			var data = checkStatus.data;
			layer.msg('选中了：' + data.length + ' 个');
			break;
		case 'isAll':
			layer.msg(checkStatus.isAll ? '全选' : '未全选');
			break;
		}
		;
	});

	// 监听行工具事件
	table.on('tool(sysuserTable)', function(obj) {
		var data = obj.data;
		if (obj.event === 'del') {
			layer.confirm('真的删除项目吗？', function(index) {
				obj.del();
				projectDelete(data.pro ,data.status);
				layer.close(index);
			});
		} else if (obj.event === 'edit') {
			processInstanceIdStr = data.processInstanceId;
			$("#processInstanceHistroyRecordUl").empty();
			$("#formCalibrationDataRemarksText").val("");
			 $('#uploadFileNameUl').empty();//清空文件ul
			showHistoryRecord(data.pro);
			/* 再弹出编辑界面 */
			layer.open({
				type:1,
				title : "数据文件上传",
				skin : "editFile",
				//offset : '50px',
				shadeClose : true,
				area : ['60%','90%'],
				//btn : [ '发起项目', '取消' ],
				content : $("#calibrationDataAdd"),
				success: function(layero,index){
					layerIndex = index;
			    	$('#formProgrameRemarksText').val("");
			    	table.reload('globalFileTableReload',{
						where: { //设定异步数据接口的额外参数，任意设
							processInstanceId: data.pro
						  }
				   });
				},		
			    });
		} else if (obj.event === 'operationRecord') {
			var pro =  data.pro;
			layer.open({
				type : 1,
				area : [ "575px", '400px' ],
				title : "审批流程",
				id : "haha",
				maxmin : false,
				content : '<div><table id="templateTable"></table></div>',
				success : function(index, layero) {
					table.render({
						elem : '#templateTable',
						width : '100%',
						url : '../../activiti/operationRecord?processInstanceId=' + pro,// 数据接口、
						cols : [ [ // 表头
						{
							field : 'assignee',
							title : '操作人',
							width : 100,
							fixed : 'left',
							unresize : true,
							align : 'center'
						}, {
							field : 'activityName',
							width : 150,
							title : '流程节点',
							align : 'center'
						}, {
							field : 'startTime',
							width : 160,
							title : '开始时间',
							align : 'center'
						}, {
							field : 'endTime',
							width : 160,
							title : '结束时间',
							align : 'center'
						}, ] ]
					});
				}
			});
		}
	});

	$('.userTable .layui-btn').on('click', function() {
		var type = $(this).data('type');
		active[type] ? active[type].call(this) : '';
	});

	function projectDelete(id, status) {
		if(status == 0){
			layer.msg('该项目已被删除');
			return;
		} else if (status == 2){
			layer.msg('已完成项目不可删除');
			return;
		}
		$.ajax({
			url : '../../activiti/delectExample?processInstanceId=' + id,
			contentType : "application/json;charset=utf-8",
			type : 'post',
			success : function(data) {
				var json = JSON.parse(data);
				if (json.code == '0') {
					layer.msg('删除项目成功');
				} else {
					layer.msg('删除项目失败');
				}
			}
		})
	}

	// 监听姓名的输入框
	$('#nameText').on("input propertychange", function() {
		active.reload();
	});
	$('#numberText').on("input propertychange", function() {
		active.reload();
	});
	form.on('select(project_nameTypeTextFilter)', function(){
		$('#platform_name').val('');
		form.render('select');
		active.reload();
	});
	form.on('select(platformTypeTextFilter)', function(){
		$('#project_name').val('');
		form.render('select');
		active.reload();
	});
	form.on('select(projectTypeTextFilter)', function(){
		active.reload();
	});
	form.render('select');
	
	 /**展示历史节点记录*/
	   function showHistoryRecord(processInstanceId){
		   var json = {}; 
		   json["processInstanceId"] = processInstanceId;
		   $.ajax({ 
		       type: "post", 
		       url: "../../activiti/findProcessInstanceHistoryRecord", 
		       contentType: "application/json; charset=utf-8",
		       dataType: "json",
		       async:false, 
		       data: JSON.stringify(json), 
		       success: function(result){
		    	  var processInstanceHistroyRecordUl = $("#processInstanceHistroyRecordUl");
		    	  var data = result.data;
		    	  for(var i=0;i<data.length;i++){		    		 
		    		  processInstanceHistroyRecordUl.append(" <li class='layui-timeline-item' > <i class='layui-icon layui-timeline-axis'>&#xe63f;</i><div class='layui-timeline-content layui-text' id='histroyRecordUlDiv"+ i + "'></div></li>");
		    		  var histroyRecordUl = $("#histroyRecordUlDiv" + i);
		    		  var approval = data[i].approval;
		    		  if(approval == null || approval == ""){
		    			  approval = "";
		    		  }else{
		    			  if(approval == "0"){
		    				  approval = "<font color='#00AEAE'>通过</font>";
		    			  }else{
		    				  approval = "<font color='red'>不通过</font>";
		    			  }
		    		  }	    		  
		    		  histroyRecordUl.append(" <h3 class='layui-timeline-title'><font color='#00AEAE'>" + data[i].taskName + "&nbsp;&nbsp;&nbsp;&nbsp;"+ data[i].assignee +"&nbsp;&nbsp;&nbsp;&nbsp;" + approval +"</font></h3>");
		    		  histroyRecordUl.append("<strong>时间：</strong>" + data[i].taskStartTime);
		    		  var attachments = data[i].attachments;
		    		  if(attachments.length > 0){
		    			  for(var j=0;j<attachments.length;j++){
		    				  if(j == 0){
		    					  histroyRecordUl.append("</br><strong>附件：</strong>");
		    				  }	    				  
		    				  if(j == attachments.length-1){
		    					  histroyRecordUl.append("&nbsp;&nbsp;【<a href='javascript:showAttachments(\"" + attachments[j].url + "\");'>" + attachments[j].name + "</a>】" + "&nbsp;&nbsp;");
		    					  var btnIcon = "&#xe601;";
		    					  histroyRecordUl.append("<a href='javascript:showTaskAttachmentsTable(" + data[i].taskId +")' class='layui-btn layui-btn-xs'><i class='layui-icon'>" + btnIcon + "</i></a>");
		    				  }else{
		    					  histroyRecordUl.append("&nbsp;&nbsp;【<a href='javascript:showAttachments(\"" + attachments[j].url + "\");'>" + attachments[j].name + "</a>】&nbsp;");
		    				  }
		    			  }
		    		  }
		    		  var remarks = "";
		    		  if(data[i].remarks != null && data[i].remarks != ""){
		    			  if(i == data.length-1){
		    				  $('#formCalibrationDataRemarksText').val(data[i].remarks);
		    			  }
		    			  remarks = data[i].remarks
		    		  }
		    		  histroyRecordUl.append("</br><strong>备注：</strong>" + remarks );
		    		  var isUserEnd = true;
		    		  for(var j = data.length-1; j > i; j--){
		    			  if((result.userId + "") == data[j].userId){
		    				  isUserEnd = false;
		    			  }
		    		  }
		    		  if(isUserEnd){
		    			  break;
		    		  }
		    	  }	    	  
		       } 
			});
	   }
	   
	 //节点附件的表格
	   table.render({
		   elem: '#taskAttachmentsTable',
		   url: '../../activiti/findTaskAttachmentsTable',
		   page: false,
		   cols: [[
			   {type : 'checkbox',	fixed : 'left'},
			   {field: 'name', title: '文件名称',width: 345},
			   {field: 'time', title: '提交时间',width: 345,templet:function(d){return datetimeFormat(d.time)}},
			   {field : 'url', hide  : true},
			   { title: '操作', toolbar : '#barAttachments', width: 150 }
		   ]],
		   done : function() {	
			  
		   },
		   id:'attachmentsReload'
	   });
	   
	 //监听行工具事件
		table.on('tool(taskAttachmentsTable)', function(obj) {
			var data = obj.data;
			if (obj.event === 'del') {
			} else if (obj.event === 'downLoad') {		
				 downLoadFile(data.name,data.url);
			}
		});
		
		/**
		    * html页面调用js文件里的函数，写法必须为  方法名 = function (){}形式，其他方式写，html页面会搜索不到该函数，就会报错。
		    *  报错类型 ： function 方法名(){}   和  var 方法名 = function(){}
		    * */
		   showTaskAttachmentsTable =  function (taskId){
			   table.reload('attachmentsReload',{
					where: { //设定异步数据接口的额外参数，任意设
					    taskId: taskId
					  }
				});
				layer.open({
					type : 1,
					title : "附件列表",
					skin : "layui-layer-lan",
					offset: '150px',
					shadeClose : true,
					area : "900px",
					//maxWidth: 1000,
					maxHeight: 400,
					content : $("#taskAttachmentsTableDiv"),
					toolbar: true 
				});	  
		   }
		   
		   //下载多个文件并打包成zip
		   downLoadMutilFilesToZip = function(){
		           var list = table.cache.attachmentsReload;
		           var imgNameList = [];
		           var imgUrlList = [];
		           for(var i = 0;i<list.length;i++){
		               imgNameList.push(list[i].name);//文件名称
		               imgUrlList.push(list[i].url);//文件绝对路径
		           }
		           var paths =  encodeURI(encodeURI(imgUrlList));
		           var names = encodeURI(encodeURI(imgNameList));
		           //将名称传入后台
		           window.location.href = "../../upLoadFile/downLoadMutilFilesToZip?names="+names+"&paths="+paths;
		   }
		   
		   //验证上传的文件在这个任务节点是否已经存在
		   function validateFileExist(fileName, taskId){
			   var result = "0";
			   $.ajax({ 
			       type: "post", 
			       url: "../../upLoadFile/validateFileExist", 
			       async:false, 
			       data: {fileName: fileName, taskId:taskId}, 
			       success: function(data){
			    	   result = data;
			       }
			   }); 
			   return result;
		   }
		   
		   showAttachments = function(url){
			   url = url.substring(0,url.lastIndexOf(".")) + ".pdf";
			   url = url.substring(url.indexOf("uploadFile")-1);
			   alert(url);
			   PDFObject.embed(url,"#pdf_preview");
			   $.ajax({ 
			       type: "post", 
			       url: "../../upLoadFile/officeToPdf", 
			       async:false, 
			       data: {url:url}, 
			       success: function(data){
			    	   result = data;
			       }
			   }); 
			   layer.open({
					type : 1,
					title : "附件列表",
					skin : "myskin",
					shadeClose : true,
					area : ["70%","90%"],
					content : $("#pdf_preview"),
					toolbar : true 
				});	   
		   }
		   
		   //全局文件的表格
		   table.render({
			   elem: '#globalFileTable',
			   url: '../../activiti/findGlobalFIleTableByPid',
			   page: false,
			   cols: [[
				   {field: 'fileName', title: '文件名称'},
				   {field: 'time', title: '更新时间',templet:function(d){return datetimeFormat(d.time)}},
				   {field: 'name', title: '操作人' , width: 100},
				   {field : 'url', hide  : true},
				   { title: '操作', toolbar : '#barGlobalFile', width: 150 }
			   ]],
			   done : function() {	
			   },
			   id:'globalFileTableReload'
		   });
		   
		 //监听行工具事件
			table.on('tool(globalFileTable)', function(obj) {
				var data = obj.data;
				processInstanceFileIdStr = data.id;
				if (obj.event === 'downLoadGlobalFile') {	
					 downLoadFile(data.fileName,data.url);
				}
			});
			
			downLoadProgramFilesToZip = function(){
				var list = table.cache.globalFileTableReload;
				           var imgNameList = [];
				           var imgUrlList = [];
				           for(var i = 0;i<list.length;i++){    
					           imgNameList.push(list[i].fileName); 
					           //压缩文件不允许重名，故有重名文件则改变名字        
				               for(var j = 0; j < i; j++){
				            	   if(list[i].fileName == list[j].fileName){
				            		   imgNameList[i] = list[i].fileName.substr(0,list[i].fileName.indexOf(".")) + "_" +  i + list[i].fileName.substr(list[i].fileName.indexOf(".")) ;//文件名称
				            		   break;
				            	   }
				               }
				               imgUrlList.push(list[i].url);//文件绝对路径
				           }
				           var paths =  encodeURI(encodeURI(imgUrlList));
				           var names = encodeURI(encodeURI(imgNameList));
				           //将名称传入后台
				           window.location.href = "../../upLoadFile/downLoadMutilFilesToZip?names="+names+"&paths="+paths;
			}

});